package cn.lijiajia3515.cairo.auth.modules.resource;

import cn.lijiajia3515.cairo.auth.domain.mongo.ResourceMongo;
import cn.lijiajia3515.cairo.core.tree.TreeConverter;
import cn.lijiajia3515.cairo.mongo.data.MetaMongo;

import java.util.Comparator;
import java.util.List;
import java.util.Optional;

/**
 *
 */
public class ResourceConverter {
    static final Comparator<ResourceTreeNode> RESOURCE_TREE_COMPARATOR = Comparator.comparing(ResourceTreeNode::getSort).thenComparing(ResourceTreeNode::getId);

    public static ResourceTreeNode convert(ResourceMongo m) {
        return ResourceTreeNode.builder()
                .id(m.getId())
                .parent(m.getParent())
                .type(Optional.ofNullable(m.getType()).map(x -> ResourceType.valueOf(x.name())).orElse(null))
                .name(m.getName())
                .permissions(m.getPermissions())
                .path(m.getPath())
                .icon(m.getIcon())
                .sort(Optional.ofNullable(m.getMeta()).map(MetaMongo::getSort).orElse(0L))
                .build();
    }


    public static List<ResourceTreeNode> tree(List<ResourceTreeNode> nodes) {
        return tree(nodes, ResourceConstants.TREE_ROOT);
    }

    public static List<ResourceTreeNode> tree(List<ResourceTreeNode> nodes, String root) {
        return TreeConverter.build(nodes, root, RESOURCE_TREE_COMPARATOR);
    }

}
